<template>
  <div class="home-container">
    <div class="left">
      <!-- 头像 -->
      <div class="item">
        <el-tooltip 
            effect="dark"
            placement="right" 
            :enterable="true"
        >   
            <template #content>
                <div class="avatar-tip-box">
                  <div class="avatar-tip-item" @click="doOpenPersonalDataDialog">个人资料</div>
                  <div class="avatar-tip-item" @click="openUpdPwdDialog = true">修改密码</div>
                  <div class="avatar-tip-item" @click="doLogout">退出登录</div>
                </div>
            </template>
            <el-avatar v-if="UserState.loginUser.avatar" shape="circle" :src="UserState.loginUser.avatar" />
            <el-avatar v-else>
              <el-icon color="#83B7F7" :size="28"><UserFilled/></el-icon>
            </el-avatar>
        </el-tooltip>
      </div>

      <!-- 消息 -->
      <div class="item count-container" @click="$router.push('/home/chat')">
        <el-tooltip
          effect="dark"
          content="消息"
          placement="right"
        >
          <el-icon :style="{color: UserState.unreadCount > 0 ? '#FF0000' : '#fff'}" class="icon"><ChatDotRound/></el-icon>
        </el-tooltip>
        <div v-if="UserState.unreadCount > 0" class="count-box">{{ UserState.unreadCount > 99 ? '99+' : UserState.unreadCount }}</div>
      </div>

      <!-- 通讯录 -->
      <div class="item" @click="$router.push('/home/user')">
        <el-tooltip
          effect="dark"
          content="通讯录"
          placement="right"
        >
          <el-icon class="icon"><User/></el-icon>
        </el-tooltip>
      </div>

      <!-- 日志 -->
      <div class="item" @click="$router.push('/home/memo')">
        <el-tooltip
          effect="dark"
          content="备忘薄"
          placement="right"
        >
          <el-icon class="icon"><Notebook/></el-icon>
        </el-tooltip>
      </div>

    </div>
    <div class="right">
      <router-view></router-view>
    </div>


    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="openUpdPwdDialog"
      title="修改密码"
      width="300"
      :draggable="true"
      :modal="false"
    >
      <div class="edit-box">
        <div class="edit-item">
          <div class="item-label">原密码：</div>
          <div class="item-value"><el-input size="small" type="password" v-model="updPwdParam.oldPwd" placeholder="请输入原密码" clearable/></div>
        </div>
        <div class="edit-item">
          <div class="item-label">新密码：</div>
          <div class="item-value"><el-input size="small" type="password" v-model="updPwdParam.newPwd" placeholder="请输入新密码" clearable/></div>
        </div>
        <div class="edit-item">
          <div class="item-label">确认密码：</div>
          <div class="item-value"><el-input size="small" type="password" v-model="updPwdParam.newPwd2" placeholder="请输入确认密码" clearable/></div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" type="info" @click="openUpdPwdDialog = false">取消</el-button>
          <el-button size="small" type="primary" @click="doUpdPwd">确认</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 个人资料 -->
    <personal-data
      title="个人资料"
      v-model:visible="openPersonalDataDialog"
      v-model:mode="personalDataEditMode"
      :user="personalData"
    />


  </div>
    
</template>

<script setup>
// 导入
import { ref,onMounted } from 'vue'
import { ChatDotRound,User,UserFilled,Notebook } from '@element-plus/icons-vue'
import { $msg_e,$msg_s } from '../utils/msg.js'
import { $get,$post } from '../utils/request.js'
import { UserState } from '../store/loginUser.js'
import { useRouter } from 'vue-router'
import { UserApi,ConfigApi, MessageApi, AuthApi } from '@/api/path.js'
import { SocketIo } from '@/utils/socket.js'
import PersonalData from './PersonalData.vue'


// 初始化
const router = useRouter()


// 数据
const loginUser = ref({
  id:'',
  username:'',
  deptId:'',
  deptName:'',
  avatar:''
})
const openUpdPwdDialog = ref(false)
const updPwdParam = ref({
  oldPwd:'',
  newPwd:'',
  newPwd2:''
})

const openPersonalDataDialog = ref(false)
// 0-默认，1-查看，2-编辑
const personalDataEditMode = ref(0)
const personalData = ref()



// 获取登录用户信息
const getLoginUserInfo = async () => {
  const res = await $get(UserApi.getLoginUserInfo);
  console.log('getLoginUserInfo-res:',res);
  if(!res.success){
    return $msg_e(res.message)
  }
  loginUser.value = res.data
  // 设置登录用户全局状态管理
  UserState.setUserInfo(res.data)
}

// 登出
const doLogout = async () => {
  // 调用后端退出接口
  const res = await $get(AuthApi.logout)
  if(!res.success){
    return $msg_e(res.message)
  }

  // 移除前端缓存token
  window.localStorage.removeItem('token')
  window.socket.close()
  // 跳转回登录页
  location.href = './login.html'
}

// 更新密码
const doUpdPwd = async () => {
  // 校验
  if(!updPwdParam.value.oldPwd){
    return $msg_e('请输入原密码')
  }
  if(!updPwdParam.value.newPwd){
    return $msg_e('请输入新密码')
  }
  if(!updPwdParam.value.newPwd2){
    return $msg_e('请输入确认密码')
  }
  if(updPwdParam.value.newPwd != updPwdParam.value.newPwd2){
    return $msg_e('新密码和确认密码不一致')
  }
  const res = await $post(UserApi.updPwd, updPwdParam.value)
  if(!res.success){
    return $msg_e(res.message)
  }
  $msg_s('修改密码成功')
  // 退出登录
  doLogout()
}

// 打开个人资料对话框
const doOpenPersonalDataDialog = () => {
  personalData.value = {
    id: UserState.loginUser.id,
    username: UserState.loginUser.username,
    deptName: UserState.loginUser.deptName,
    avatar: UserState.loginUser.avatar,
    job: UserState.loginUser.job
  }
  openPersonalDataDialog.value = true
  personalDataEditMode.value = 1
}


// 初始化socket监听事件
const initSocketListener = () => {
  window.socket.on('count', msg => {
    console.log('监听count事件接收到消息: ', msg);
    UserState.setUnreadCount(msg.count)
  })

  window.socket.on('server_logout', msg => {
    console.log('监听server_logout事件接收到消息: ', msg);
    localStorage.removeItem('token')
    location.href = './login.html'
  })
}

// 初始化用户未读数据
const initUnreadCount = async () => {
  const res = await $get(MessageApi.getUnreadCount)
  if(!res.success){
    console.log('查询用户未读计数出错')
    return $msg_e(res.message)
  }
  UserState.setUnreadCount(res.data)
}

// 请求获取浏览器通知权限
const requestNotificationPermission = () => {
  // 检查浏览器是否支持通知
  if (!("Notification" in window)) {
    console.log("此浏览器不支持通知。");
    return;
  }
  console.log('requestNotificationPermission: ' + Notification.permission)
  if (Notification.permission === "default") {
    Notification.requestPermission().then(permission => {
      console.log('permission:' + permission)
      if (permission === "granted") {
        console.log("通知权限已授予");
      } else {
        console.log("用户拒绝了通知权限");
      }
    });
  }
}


// 生命周期
onMounted(() => {
  getLoginUserInfo();
  initSocketListener();
  initUnreadCount();
  requestNotificationPermission();
})



</script>

<style scoped lang="scss">
.home-container{
  height: 100%;
  display: flex;/**声明为弹性容器 */
  flex-direction: row; /**定义主轴方向是水平从左到右 */
  overflow: hidden; /**限制外层容器在垂直和水平方向都不能出现滚动条 */
  & > .left{
    width: 40px;
    background-color: #3975C6;
    padding: 15px 10px;
    display: flex;
    flex-direction: column; /**定义主轴方向是垂直从上到下（即让元素从上到下排列） */
    justify-content: start;
    align-items: center; /**控制交叉轴（即水平方向）居中 */
    & > .item{
      width: 100%;
      display: flex;
      flex-direction: row;
      justify-content: center;
      margin-bottom: 15px;
      & > .icon{
        color: #fff;
        font-size: 25px; /**控制图标大小（可以把图标看成是一种字体） */
        cursor: pointer;
      }
      & > .el-avatar{
        --el-avatar-bg-color:#fff /**设置头像的背景颜色为白底 */
      }
    }
  }
  & > .right{
    flex: 1;
    height: 100%;
  }
}

.avatar-tip-box{
  display: flex;
  flex-direction: column;
  padding-top: 5px;
  .avatar-tip-item{
    margin-bottom: 5px;
    cursor: pointer;
  }
  .avatar-tip-item:hover{
    color: lightgreen;
  }
}


.count-container{
  position: relative;
  & > .count-box{
    width: 20px;
    height: 14px;
    border-radius: 7px;
    font-size: 9px;
    position: absolute;
    right: 0;
    top: 0;
    transform: translate(10%,-30%);
    background-color: red;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}


</style>